package startup

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	glogger "gorm.io/gorm/logger"
	"time"
	"webook/internal/repository/dao"
	"webook/pkg/logx"
)

func InitDB(l logx.LoggerX) *gorm.DB {
	db, err := gorm.Open(mysql.Open("root:QWEzxc123456@tcp(localhost:3306)/webook"), &gorm.Config{
		Logger: glogger.New(GORMLoggerFunc(l.Debug), glogger.Config{
			// 慢SQL阈值 这里设置成50ms
			// SQL查询要求命中索引，一次磁盘IO是10ms
			SlowThreshold: 50 * time.Millisecond,
			// 忽略记录找不到的日志
			IgnoreRecordNotFoundError: true,
			// 查询条件参数话
			ParameterizedQueries: true,
			// 最低的日志打印级别
			LogLevel: glogger.Info,
		}),
	})
	if err != nil {
		panic(err)
	}
	dao.InitTables(db)
	return db
}

type GORMLoggerFunc func(msg string, args ...logx.Field)

func (fn GORMLoggerFunc) Printf(msg string, args ...interface{}) {
	fn(msg, logx.Field{
		Key:   "args",
		Value: args,
	})
}
